package com.magicborrow.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.magicborrow.BaseLog;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.adapter.AddImgAdapter;
import com.magicborrow.beans.AddressBean;
import com.magicborrow.beans.BaseBean;
import com.magicborrow.beans.StringBean;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.beans.StuffResult;
import com.magicborrow.beans.TagBean;
import com.magicborrow.beans.UserBean;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.huanxin.Constant;
import com.magicborrow.utils.HttpRequest;
import com.magicborrow.utils.ImageUploadAsyncTask;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.InputPriceDialog;
import com.magicborrow.views.LoadingDialog;
import com.magicborrow.views.MsgDialog;
import com.magicborrow.views.SuccessDialog;
import com.photoselector.model.PhotoModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PushStuffActivity extends BaseActivity implements View.OnClickListener {
    //  private TableLayout llImg;
    private ImageView imvAdd;
    private LinearLayout llTagBoot;
    private LinearLayout llTagText;
    private LinearLayout llAddress;
    private TextView tvAddress;
    private EditText tvDeposit;
    private TextView tvRent;
    private ArrayList<PhotoModel> photoModels = new ArrayList<>();
    private ArrayList<Integer> removeImageId;
    //   private TableRow.LayoutParams params;
    private ArrayList<String> tags;
    private ArrayList<Integer> tagIds;
    private AddressBean address;
    private int price = 0;
    private int priceMode;
    private LoadingDialog dialog;
    private StuffBean data;
    private RecyclerView recyclerView;
    private AddImgAdapter adapter;
    private TextView tvTitle;
    private Button btnPush;
    private boolean priceCan0;
    private boolean rentCan0;
    private CheckBox cbDangmian;
    private CheckBox cbKuaidi;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_push_stuff);

        initView();
        initListener();
        initData();


    }

    private void initData() {
        Intent intent = getIntent();
        if (intent.hasExtra("data")) {
            data = (StuffBean) intent.getSerializableExtra("data");
            getEtStuffName().setText(data.getName());
            getEtStuffInfo().setText(data.getDescription());
            tvAddress.setText(data.getAddress());
            address = new AddressBean();
            address.setAddress(data.getAddress());
            address.setLat(data.getLat());
            address.setLon(data.getLon());
            //   address.setAddressInfo(data.get);
            tvDeposit.setText(data.getDeposit() + "");
            tvTitle.setText("编辑求借物品");
            btnPush.setText("发布物品");
            tagIds = new ArrayList<>();
            tags = new ArrayList<>();
            for (TagBean bean : data.getTags()) {
                tagIds.add(bean.getId());
                tags.add(bean.getName());

            }
            createTags();


            price = data.getPrice();
            priceMode = data.getPriceMode();
            tvRent.setText("￥" + data.getPrice() + "/" + PriceModeEnum.getModeStr(data.getPriceMode()));

            adapter = new AddImgAdapter(this, (ArrayList<StuffBean.ImagesEntity>) data.getImages(), recyclerView);

        } else {
            adapter = new AddImgAdapter(this, null, recyclerView);

        }
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

    }

    private void initListener() {
        findViewById(R.id.btn_keeps).setOnClickListener(this);
        //  imvAdd.setOnClickListener(this);
        llTagBoot.setOnClickListener(this);
        tvRent.setOnClickListener(this);
        tvAddress.setOnClickListener(this);
        cbKuaidi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(!isChecked){
                    cbDangmian.setEnabled(false);
                }

            }
        });
        cbDangmian.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if(!isChecked) cbKuaidi.setEnabled(false);
            }
        });
    }

    private void initView() {
        cbDangmian = (CheckBox) findViewById(R.id.cb_dangmian);
        cbKuaidi = (CheckBox) findViewById(R.id.cb_kuaidi);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        recyclerView = (RecyclerView) findViewById(R.id.rc_add);
        //llImg = (TableLayout) findViewById(R.id.ll_img);
        // imvAdd = (ImageView) findViewById(R.id.imv_add);
        llTagBoot = (LinearLayout) findViewById(R.id.ll_tag_boot);
        llTagText = (LinearLayout) findViewById(R.id.ll_tag_text);
        llAddress = (LinearLayout) findViewById(R.id.ll_address);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        tvDeposit = (EditText) findViewById(R.id.tv_deposit);
        tvRent = (TextView) findViewById(R.id.tv_rent);
        btnPush = (Button) findViewById(R.id.btn_push);
        btnPush.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.tv_address:
                intent = new Intent(this, AddressManagerActivity.class);
                startActivityForResult(intent, 2);
                break;

            case R.id.ll_tag_boot:
                intent = new Intent(this, TagActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.btn_keeps:
                publishStuff(0);
             /*   SuccessDialog sDialog = new SuccessDialog(this, "保存至草稿箱", R.mipmap.keeps_sucess);
                sDialog.show();

                sDialog.setOnViewPostsClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });*/


                //TODO implement
                break;

            case R.id.tv_rent:
                List<String> data = new ArrayList<>();
                data.add("小时");
                data.add("天");
                data.add("周");
              /*  data.add("月");*/
                final InputPriceDialog dialog = new InputPriceDialog(this, data);
                dialog.show();
                dialog.setOnOkClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        price = dialog.getTimeNumber();
                        priceMode = PriceModeEnum.getModeId(dialog.getCurrentPriceMode());
                        dialog.dismiss();
                        tvRent.setText("￥" + price + "/" + dialog.getCurrentPriceMode());

                    }
                });
                break;
            case R.id.btn_push:
                publishStuff(1);

                //TODO implement
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 2) {
                address = (AddressBean) data.getSerializableExtra("address");
                tvAddress.setText(address.getAddress() + "\n" + address.getAddressInfo());
                return;
            }

            if (requestCode == 1) {
                tags = data.getStringArrayListExtra("tags");
                tagIds = data.getIntegerArrayListExtra("tagsId");
                llTagText.removeAllViews();
                if (tags != null) {
                    createTags();
                }
                return;
            }
            ArrayList<PhotoModel> photos = (ArrayList<PhotoModel>) data.getSerializableExtra("photos");

            if (photos != null) {

                for (PhotoModel photo : photos) {
                    adapter.addData(photo.getOriginalPath());
                }

                photoModels.addAll(photos);
            }
        }
    }

    private void createTags() {
        llTagText.removeAllViews();
        for (String s : tags) {
            TextView tv = new TextView(this);
            tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.tag_bg));
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.text_size_small_s));
            tv.setTextColor(getResources().getColor(R.color.orange_red));
          /*  ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            tv.setLayoutParams(params);*/

            Log.i("tag", s);
            tv.setText("" + s);
            llTagText.addView(tv);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
            params.setMargins(getResources().getDimensionPixelOffset(R.dimen._5dp), 0, 0, 0);
            tv.setLayoutParams(params);
        }
    }


    private EditText getEtStuffName() {
        return (EditText) findViewById(R.id.et_stuff_name);
    }

    private EditText getEtStuffInfo() {
        return (EditText) findViewById(R.id.et_stuff_info);
    }

    private MsgDialog msgDialog;

    private void publishStuff(final int box) {

        UserBean.User user = UserTools.getUser(this);
        if (user == null || user.getId() == 0 || user.getAcc_token() == null || user.getAcc_token().isEmpty()) {
            Intent intent = new Intent(this, FirstRegisterActivity.class);
            startActivity(intent);
        }

        String name = getEtStuffName().getText().toString();
        if (TextUtils.isEmpty(name)) {
            getEtStuffName().setError("请填入物品名称");
            return;
        }


        String description = getEtStuffInfo().getText().toString();

        if (TextUtils.isEmpty(description)) {
            getEtStuffInfo().setError("描述一下您的物品吧");
            return;
        }
        String address = tvAddress.getText().toString();
        if (TextUtils.isEmpty(address)) {
            msgDialog = new MsgDialog(this, "请选择地址", null);
            msgDialog.show();

            return;
        }
        if (price == 0 && !priceCan0) {
            msgDialog = new MsgDialog(this, "确定租金为 ￥0 吗？", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    priceCan0 = true;
                    msgDialog.dismiss();
                    publishStuff(box);
                }
            });
            msgDialog.show();
            return;
        }

        int deposit = TextUtils.isEmpty(tvDeposit.getText().toString()) ? 0 : Integer.valueOf(tvDeposit.getText().toString());
        if (deposit == 0 && !rentCan0) {
            msgDialog = new MsgDialog(this, "确定押金为 ￥0 吗？", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rentCan0 = true;
                    msgDialog.dismiss();
                    publishStuff(box);

                }
            });
            msgDialog.show();
            return;
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("acc_token", UserTools.getUser(this).getAcc_token());
        params.put("name", name);
        params.put("description", description);
        params.put("address", address);
        params.put("price", "" + price);
        params.put("priceMode", "" + priceMode);
        params.put("deposit", "" + deposit);
        params.put("box", "" + box);
        int lendMode =-1;
        if(cbDangmian.isChecked()&&cbKuaidi.isChecked()){
            lendMode=2;

        }else if(cbDangmian.isChecked()){
            lendMode=0;

        }else {
            lendMode=1;
        }

        params.put("lendMode", ""+lendMode);
        params.put("lon", "" + this.address.getLon());
        params.put("lat", "" + this.address.getLat());
        String tag = "";
        for (int i = 0; i < tagIds.size(); i++) {
            tag = tag + "," + tagIds.get(i);

        }

        tag = tag.substring(1);

        Log.i("tagids", tag);
        params.put("tagIds[]", "" + tag);
        HashMap<String, File> files = new HashMap<>();
        if (adapter.getUrls().size() == 0) {
            msgDialog = new MsgDialog(this, "请至少上传一张物品图片", null);
            msgDialog.show();
            return;
        }
        for (String photo : adapter.getAddUrls()) {
            files.put(new File(photo).getName(), new File(photo));
        }

        String url = Constants.URL_POST_PUSH_STUFF;
        if (data != null) {
            url = Constants.URL_GET_UPDATE_STUFF;
            params.put("id", "" + data.getId());
            String removeId = "";
            for (int t = 0; t < adapter.getDeleteId().size(); t++) {
                removeId = removeId + "," + adapter.getDeleteId().get(t);
            }
            if (!TextUtils.isEmpty(removeId))
                removeId = removeId.substring(1);
            params.put("removeIds[]", removeId);
        }

        Log.i("params", params.toString());
        if (dialog == null)
            dialog = new LoadingDialog(this);
        dialog.show();
        BaseLog.e("url", url);
        ImageUploadAsyncTask asyncTask = new ImageUploadAsyncTask(params, files, "files[]", url,
                new HttpRequest.HttpRequestListener() {
                    @Override
                    public void httpError() {
                        showShortMsg("商品上传失败，请稍候再试");
                        dialog.dismiss();

                    }

                    @Override
                    public void httpSuccess(String msg) {
                        int code = -1;
                        String message = "服务器暂时无法链接";
                        String tid = "-1";
                        try {
                            JSONObject obj = new JSONObject(msg);
                            code = obj.getInt("code");
                            message = obj.getString("message");
                            if (code >= 0) {
                                tid = obj.getString("data");
                            }
                        } catch (JSONException e) {
                            // e.printStackTrace();
                        }
//                        Gson gson = new Gson();
//                        BaseBean bean = gson.fromJson(msg, StringBean.class);
                        if (code >= 0) {

                            Log.i("msg", msg);
                            //StringBean b = (StringBean) bean;
                            String s;

                            final String id = tid;

                            dialog.dismiss();
                            //  showShortMsg("商品上传成功");
                            if (box == 1) {
                                s = "发布成功";
                            } else {
                                s = "草稿保存成功";
                            }
                            final SuccessDialog sucessDialog = new SuccessDialog(PushStuffActivity.this, s, R.mipmap.push_sucess);
                            sucessDialog.show();
                            sucessDialog.setOnViewPostsClick(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    VolleyTool.get(Constants.URL_GET_WARE + id + "?acc_token=" + UserTools.getUser(PushStuffActivity.this).getAcc_token(),
                                            null, new VolleyTool.HTTPListener() {
                                                @Override
                                                public <T> void onResponse(T t, int requestCode) {
                                                    StuffResult baseBean = (StuffResult) t;
                                                    if (baseBean.getCode() >= 0) {
                                                        Intent intent = new Intent(PushStuffActivity.this, BorrowStuffDetailActivity.class);
                                                        intent.putExtra("data", baseBean.getData());
                                                        intent.putExtra("canEdit", true);
                                                        startActivity(intent);
                                                        finish();

                                                    } else {
                                                        if (dialog != null) {
                                                            dialog.dismiss();
                                                        }
                                                        showShortMsg(baseBean.getMessage());

                                                    }
                                                }

                                                @Override
                                                public void onErrorResponse(VolleyError error, int requestCode) {
                                                    if (dialog != null) {
                                                        dialog.dismiss();
                                                    }
                                                }
                                            }, 0, StuffResult.class);

                                }
                            });
                        } else {
                            showShortMsg(message);
                            Log.e("message", message);
                        }
                    }
                });
        asyncTask.execute();


    }

}
